package com.ica.android.ui.contact.util;

import java.io.InputStream;
import java.util.List;

import com.ica.R;
import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactArrayAdapter extends ArrayAdapter<AndroidContact> {

	/**
	 */
	private List<AndroidContact> contacts = null;
	/**
	 */
	private Context context = null;
	
	public ContactArrayAdapter(Context context, int textViewResourceId, List<AndroidContact> contacts) {
		
		super(context, textViewResourceId, contacts);
		this.contacts = contacts;
		this.context = context;
	}
	
	@Override
	// Photo doesn't work
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null) {
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.contacts_list_view, null);
        }
        AndroidContact contact = contacts.get(position);
        if (contact != null) {
        	    TextView tt = (TextView) view.findViewById(R.id.name_entry);
                TextView bt = (TextView) view.findViewById(R.id.number_entry);
                if (tt != null) {
                	tt.setText(contact.getName());                            
                }
                if(bt != null){
                	bt.setText(contact.getPhoneNumber());
                }
                InputStream photo = ContactsContract.Contacts.openContactPhotoInputStream(
                						context.getContentResolver(),
                						ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contact.getId()));
        	    ImageView photoFrame = (ImageView) view.findViewById(R.id.contactThumbnail);    
        	    if (photo!=null) {
        	    	Bitmap bitmap = BitmapFactory.decodeStream(photo);
        			photoFrame.setImageBitmap(bitmap);
        	    }
        	    else {
        	    	photoFrame.setImageResource(context.getResources().getIdentifier("ic_contact" , "drawable", context.getPackageName()));
        	    }
                view.setBackgroundColor(contact.getChecked() ? Color.DKGRAY : Color.BLACK);
        }
        return view;
    }
}
